<%--
  Created by IntelliJ IDEA.
  User: 戴金睿
  Date: 2022/11/20
  Time: 16:13
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>EShopManager</title>
    <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <link rel="stylesheet" type="text/css"
          href="${pageContext.request.contextPath}/static/lib/bootstrap/css/bootstrap.css"/>
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/stylesheets/theme.css"/>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/lib/font-awesome/css/font-awesome.css"/>
    <script src="${pageContext.request.contextPath}/static/lib/jquery-1.7.2.min.js" type="text/javascript"></script>
    <script src="${pageContext.request.contextPath}/static/lib/ckeditor/ckeditor.js" type="text/javascript"></script>

    <!-- Demo page code -->

    <style type="text/css">
        #line-chart {
            height: 300px;
            width: 800px;
            margin: 0px auto;
            margin-top: 1em;
        }

        .brand {
            font-family: georgia, serif;
        }

        .brand .first {
            color: #ccc;
            font-style: italic;
        }

        .brand .second {
            color: #fff;
            font-weight: bold;
        }
    </style>

    <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]-->
    <%--    <script src="lib/html5.js"></script>--%>
    <!-- [endif]-->

</head>
<body>


<!-- 顶部 -->
<c:import url="top.jsp"></c:import>
<!-- 左边 -->
<c:import url="left.jsp"></c:import>

<div class="content">
    <div class="header">
        <h1 class="page-title">图书管理</h1>
    </div>

    <ul class="breadcrumb">
        <li><a href="bookmanager.jsp">图书管理</a> <span class="divider">/</span></li>
        <li class="active">添加图书信息</li>
    </ul>


    <div class="container-fluid">

        <div class="row-fluid">

            <div class="btn-toolbar">
                <button class="btn btn-primary" id="btnSave">
                    <i class="icon-save"></i> 保存
                </button>
            </div>
            <div class="well">
                <ul class="nav nav-tabs">
                    <li class="active"><a href="#basicInfo" data-toggle="tab">通用信息</a></li>
                    <li><a href="#desInfo" data-toggle="tab">详细描述</a></li>
                    <li><a href="#otherInfo" data-toggle="tab">其他信息</a></li>
                </ul>

                <!-- 通用信息 -->
                <div id="myTabContent" class="tab-content">
                    <div class="tab-pane active in" id="basicInfo">
                        <form id="uploadForm" enctype="multipart/form-data">
                            <label>书籍名称</label>
                            <input type="text" name="book_name" class="input-xlarge" value="${tbBook.bookName}">

                            <%--                            <!-- 有二级分类 -->--%>
                            <%--                            <c:when test="${tbBook.tbType.typeId!='' and tbBook.tbType.typeId!=null and tbBook.tbType.typeId>11}">--%>
                            <%--                                <!-- 取出二级id 所依赖的一级id -->--%>
                            <%--                                <c:set var="childTypeId" scope="request">--%>
                            <%--                                    ${tbBook.tbType.parentId}--%>
                            <%--                                </c:set>--%>
                            <%--                                <c:set var="levelOneTypeId" scope="request">--%>
                            <%--                                    <c:if test=" ${tbBook.tbType.}"--%>
                            <%--                                </c:set>--%>
                            <%--                            </c:when>--%>

                            <label>书籍分类</label>
                            <select name="parent_type_id" id="DropDownTimezone1" class="input-xlarge">
                                <c:choose>
                                    <%-- 只是一级分类--%>
                                    <c:when test="${tbBook.tbType.typeId!='' and tbBook.tbType.typeId!=null and tbBook.tbType.typeId<=11 and tbBook.tbType.typeId>=0}">
                                        <option value="${tbBook.tbType.typeId}">${tbBook.tbType.typeName}</option>
                                    </c:when>
                                </c:choose>
                            </select>

                            <select name="type_id" id="DropDownTimezone2" class="input-xlarge">
                                <c:choose>
                                    <c:when test="${tbBook.tbType.tbType.typeId!='' and tbBook.tbType.typeId!=null and tbBook.tbType.typeId>11}">
                                        <option value="${tbBook.tbType.typeId}">${tbBook.tbType.typeName}</option>
                                    </c:when>
                                    <c:otherwise>
                                        <option value=''>--请选择子分类--</option>
                                    </c:otherwise>
                                </c:choose>

                            </select>

                            <label>本店售价</label>
                            <input type="text" name="book_price" class="input-xlarge" value="${tbBook.bookPrice}">

                            <label>市场价</label>
                            <input type="text" name="book_price_old" class="input-xlarge"
                                   value="${tbBook.bookPriceOld}">

                            <label>作者</label>
                            <input type="text" name="book_author" class="input-xlarge" value="${tbBook.bookAuthor}">

                            <label>出版社</label>
                            <input type="text" name="book_press" class="input-xlarge" value="${tbBook.bookPress}">

                            <label>上传商品图片</label>
                            <input type="file" name="book_logo_big"
                                   placeholder="请选择商品图片" class="input-xlarge" value="${tbBook.bookLogoBig}"/>

                            <label>上传商品缩略图</label>
                            <input type="file" name="book_logo_small"
                                   placeholder="请选择商品缩略图" class="input-xlarge"/>

                        </form>
                    </div>

                    <!-- 详细描述 -->
                    <div class="tab-pane fade" id="desInfo">
                        <form id="tab2">
                            <textarea name="book_description" style="width: 90%" cols="10" rows="20">
                                ${tbBook.bookDescription}
                            </textarea>
                            <!--
                            <script type="text/javascript">
                                CKEDITOR.replace('book_description');
                            </script>
                            -->
                        </form>

                        <iframe id="api_iframe_51240" name="api_iframe_51240" src="" width="90%" height="500px"
                                scrolling="no" frameborder="0"></iframe>
                        <script type="text/javascript">
                            //接口生成：https://www.51240.com/api/
                            document.getElementById("api_iframe_51240").src = "https://www.51240.com/apiiframe/?api_from=51240&api_url=https://zaixianwangyebianji.51240.com/&api_width=98%&api_backgroundcolor=FFFFFF";
                        </script>

                    </div>

                    <!-- 其他信息 -->
                    <div class="tab-pane fade" id="otherInfo">
                        <form id="uploadForm2">
                            <label>上传商品子图</label>
                            <input type="file" name="pic_name1" class="input-xlarge"/>
                            <input type="file" name="pic_name2" class="input-xlarge"/>
                            <input type="file" name="pic_name3" class="input-xlarge"/>
                            <input type="file" name="pic_name4" class="input-xlarge"/>
                            <input type="file" name="pic_name5" class="input-xlarge"/>
                            <br/><br/>

                            <label>商品库存数量</label>
                            <input type="text" name="store_count" value="${tbBook.storeCount}" class="input-xlarge"/>
                            <br/><br/>

                            <label>
                                是否新品：&nbsp;&nbsp;
                                <%--                                <c:choose>--%>
                                <%--                                    <c:when test="${tbBook.isNew!=0}">--%>
                                <%--                                        <input type="radio" name="is_new" value="1" checked="checked"/>是&nbsp;&nbsp;--%>
                                <%--                                        <input type="radio" name="is_new" value="0" />否--%>
                                <%--                                    </c:when>--%>
                                <%--                                    <c:otherwise>--%>
                                <%--                                        <input type="radio" name="is_new" value="1" />是&nbsp;&nbsp;--%>
                                <%--                                        <input type="radio" name="is_new" value="0" checked="checked"/>否--%>
                                <%--                                    </c:otherwise>--%>
                                <%--                                </c:choose>--%>
                                <input type="radio" name="is_new" value="1"  ${tbBook.isNew>0?'checked':''}/>是&nbsp;&nbsp;
                                <input type="radio" name="is_new" value="0"  ${tbBook.isNew==0?'checked':''}/>否
                            </label>
                            <br/>

                            <label>
                                是否热销：&nbsp;&nbsp;
                                <%--                                <c:choose>--%>
                                <%--                                    <c:when test="${tbBook.isHot!=0}">--%>
                                <%--                                        <input type="radio" name="is_hot" value="10" checked="checked"/>是&nbsp;&nbsp;--%>
                                <%--                                        <input type="radio" name="is_hot" value="0"/>否--%>
                                <%--                                    </c:when>--%>
                                <%--                                    <c:otherwise>--%>
                                <%--                                        <input type="radio" name="is_new" value="10"/>是&nbsp;&nbsp;--%>
                                <%--                                        <input type="radio" name="is_new" value="0" checked="checked" />否--%>
                                <%--                                    </c:otherwise>--%>
                                <%--                                </c:choose>--%>
                                <input type="radio" name="is_hot" value="10" ${tbBook.isHot>0?'checked':''}/>是&nbsp;&nbsp;
                                <input type="radio" name="is_hot" value="0" ${tbBook.isHot==0?'checked':''}/>否
                            </label>
                            <br/>

                            <label>
                                上架：&nbsp;&nbsp;
                                <input type="checkbox" name="status" value="1" ${tbBook.status==1?'checked':''}/>
                                打勾表示允许销售，否则不允许销售
                            </label>

                        </form>
                    </div>


                </div>

            </div>

        </div>
        <!-- 底部 -->
        <c:import url="footer.jsp"></c:import>
    </div>

</div>


<script src="${pageContext.request.contextPath}/static/lib/bootstrap/js/bootstrap.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/lib/tooltips.js"></script>

<script type="text/javascript">
    //$("[rel=tooltip]").tooltip();


    $(function () {
        //加载一级分类列表
        var url = "${pageContext.request.contextPath}/AddBookController/selectBook";
        // var data={
        //       type_id:0
        // };

        $.get(url, function (response) {
           // console.log(response)
            var jsonData = response;// var jsonData = $.parseJSON(response);解析JSON字符串 此处为一个数组
           // console.log(jsonData)
            var selectInnerHTML = "<option value=''>--请选择分类--</option>";
            for (var i = 0; i < jsonData.length; i++) {
                var typeInfo = jsonData[i];
                selectInnerHTML += "<option value='" + typeInfo.typeId + "'>" + typeInfo.typeName + "</option>";
            }
            $("select[name='parent_type_id']").html(selectInnerHTML);

        });

        //加载二级分类列表
        $("select[name='parent_type_id']").change(function () {
            var type_id = $(this).children('option:selected').val();//这就是selected的值
            var data2 = {
                type_id: type_id
            };
            url = "${pageContext.request.contextPath}/AddBookController/selectBookTwo";
            $.post(url, data2, function (response) {
                var jsonData =response;

                var selectInnerHTML = "<option value=''>--请选择子分类--</option>";
                for (var i = 0; i < jsonData.length; i++) {
                    var typeInfo = jsonData[i];
                    selectInnerHTML += "<option value='" + typeInfo.typeId + "'>" + typeInfo.typeName + "</option>";
                }
                $("select[name='type_id']").html(selectInnerHTML);

            });
        });

        /* //加载二级分类列表
         $("select[name='parent_type_id']").change(function () {
             var type_id = $(this).children('option:selected').val();//这就是selected的值
             var selectInnerHTML = "<option value='-1'>--请选择子分类--</option>";
             for (var i = 0; i < jsonData.length; i++) {
                 var type = jsonData[i]  //循环数组里的每个对象
                 if (type.typeId == type_id) { //找到一级下拉框当前选中的的对象 所在数组内的下标
                     //如果找到
                     //判断是否存在子分类
                     if (type.tbType.length != 0) {
                         //存在子分类
                         for (var j = 0; j < type.tbType.length; j++) {
                             //循环当前对象内对应的子分类
                             var childType = type.tbType[j]
                             selectInnerHTML += "<option value='" + childType.typeId + "'>" + childType.typeName + "</option>";
                         }
                     } else {
                         selectInnerHTML += "<option value='-1'>" + "当前无子分类" + "</option>";
                     }
                 }

             }
             $("select[name='type_id']").html(selectInnerHTML);

         });*/
    })

    $(function () {
        $('.demo-cancel-click').click(function () {
            return false;
        });

        //打包数据
        $("#btnSave").click(function () {
            var book_name = $("input[name='book_name']").val();
            var type_id = $("select[name='type_id']").val();
            var book_price = $("input[name='book_price']").val();
            var book_price_old = $("input[name='book_price_old']").val();
            var book_author = $("input[name='book_author']").val();
            var book_press = $("input[name='book_press']").val();
            var book_logo_big = $("input[name='book_logo_big']").val();
            var book_logo_small = $("input[name='book_logo_small']").val();
            //var book_description=CKEDITOR.instances.book_description.getData();

            var book_description = $("textarea[name='book_description']").val();
            //alert(book_description);
            //return;

            var store_count = $("input[name='store_count']").val();
            var is_new = $("input[name='is_new']:checked").val();
            var is_hot = $("input[name='is_hot']:checked").val();
            var status = 0;
            if ($("input[name='status']").get(0).checked) {
                status = 1;
            }


            if (book_name == '') {
                show_err_msg('请输入书籍名称');
            } else if (type_id == '') {
                show_err_msg('请先选择书籍分类，再选择子分类');
            } else if (book_price == '') {
                show_err_msg('请输入售价');
            } else if (book_price_old == '') {
                show_err_msg('请输入市场价');
            } else if (book_author == '') {
                show_err_msg('请输入作者');
            } else if (book_press == '') {
                show_err_msg('请输入出版社');
            } else if (book_logo_big == '') {
                show_err_msg('请选择商品图片');
            } else if (book_logo_small == '') {
                show_err_msg('请选择商品缩略图');
            } else if (book_description == '') {
                show_err_msg('请输入详细描述');
            } else if (store_count == '') {
                show_err_msg('请输入商品库存');
            } else {
                show_loading();
                uploadImg(book_name, type_id, book_price, book_price_old, book_author, book_press, book_description,
                    store_count, is_new, is_hot, status, book_logo_big, book_logo_small);
            }
        });
    });

    //上传图片
    function uploadImg(book_name, type_id, book_price, book_price_old, book_author, book_press, book_description,
                       store_count, is_new, is_hot, status, book_logo_big, book_logo_small) {
        var headFile = book_logo_big.substr(book_logo_big.indexOf("."));
        var footFile = book_logo_small.substr(book_logo_small.indexOf("."));
        if ((headFile == '.jpg' || headFile == '.jpeg' || headFile == '.png') || (footFile == '.jpg' || footFile == '.jpeg' || footFile == '.png')) {
            //开始上传图片
            show_loading();
            var formData = new FormData();
            formData.append("book_logo_big", $("input[name='book_logo_big']")[0].files[0]);
            formData.append("book_logo_small", $("input[name='book_logo_small']")[0].files[0]);
            // console.log(formData.get("fileImgBig"))
            // console.log(formData.get("fileImgSmall"))
            $.ajax({
                url: '${pageContext.request.contextPath}/PicLoadController/picload',  //上传图片
                type: 'POST',
                cache: false,
                processData : false,  //必须false才会避开jQuery对 formdata 的默认处理
                contentType : false,  //必须false才会自动加上正确的Content-Type
                data: formData
            }).done(function (res) {
                //后端应该一个图片名字数组
                // console.log(res)
                if (res.length > 0) {
                    requestAddBook(book_name, type_id, book_price, book_price_old, book_author, book_press,
                        res[0], res[1], book_description,
                        store_count, is_new, is_hot, status);
                } else {
                    show_err_msg('上传图片失败');
                }
            }).fail(function (res) {
                show_err_msg('上传图片失败');
            });

        } else {
            show_err_msg('不支持该图片类型，请上传jpg、jpeg、png格式的图片');
        }

    }

    //上传数据
    function requestAddBook(book_name, type_id, book_price, book_price_old, book_author, book_press,
                            book_logo_big, book_logo_small, book_description,
                            store_count, is_new, is_hot, status) {
        //ajax请求servlet
        var url = "${pageContext.request.contextPath}/AddBookController/addBook";
        var data = {
            bookName: book_name,
            tbType: {typeId:type_id},
            bookPrice: book_price,
            bookPriceOld: book_price_old,
            bookAuthor: book_author,
            bookPress: book_press,
            bookLogoBig: book_logo_big,
            bookLogoSmall: book_logo_small,
            bookDescription: book_description,
            storeCount: store_count,
            isNew: is_new,
            isHot: is_hot,
            status: status
        };

        //先上传文本数据和两张主图
        $.ajax({
            url:url,
            type:'post',
            data:JSON.stringify(data),
            contentType: "application/json; charset=UTF-8",
            dataType:'json'
        }).done(function (response) {
            // console.log(response)
            // var jsonData = $.parseJSON(response);
            var jsonData = response;
            //var result = jsonData.status;
            //console.log(jsonData)
            // console.log(result)
            var responseUrl = "${pageContext.request.contextPath}/AddBookController/forward";
            if (jsonData.effectRow > 0) {
                var pic_name1 =  $("input[name='pic_name1']")[0].files[0]
                var pic_name2 =  $("input[name='pic_name2']")[0].files[0]
                var pic_name3 =  $("input[name='pic_name3']")[0].files[0]
                var pic_name4 =  $("input[name='pic_name4']")[0].files[0]
                var pic_name5 =  $("input[name='pic_name5']")[0].files[0]
                var formData = new FormData();
                //随便写个外围的if
                if (pic_name1!='' || pic_name2!='' || pic_name3!='' || pic_name4!='' || pic_name5!='') {
                    if (pic_name1 != '' && pic_name1 != null) {
                        formData.append("pic_names", pic_name1)
                    }
                    if (pic_name2 != '' && pic_name2 != null) {
                        formData.append("pic_names", pic_name2)
                    }
                    if (pic_name3 != '' && pic_name3 != null) {
                        formData.append("pic_names", pic_name3)
                    }
                    if (pic_name4 != '' && pic_name4 != null) {
                        formData.append("pic_names", pic_name4)
                    }
                    if (pic_name5 != '' && pic_name5 != null) {
                        formData.append("pic_names", pic_name5)
                    }
                    var book_id = jsonData.book_id;
                    // console.log(formData)
                    //上传商品子图
                    uploadOtherImgs(formData, book_id);
                } else {
                    show_msg('操作成功', responseUrl);
                }

            } else {
                show_err_msg('操作失败');
            }
        })
    }

    //上传商品子图
    function uploadOtherImgs(formData, book_id) {
        //console.log(formData.get("pic_name1"))
       // console.log(formData.get("pic_name5"))
        var responseUrl = "${pageContext.request.contextPath}/AddBookController/forward";
        //开始上传图片
        show_loading();
            $.ajax({
                url: '${pageContext.request.contextPath}/PicLoadController/picload',
                type: 'POST',
                cache: false,
                data: formData,
                processData: false,
                contentType: false
            }).done(function (res) {
                //var jsonData = $.parseJSON(res);
               // console.log(res)
                if (res.length >= 0) {
                    var picArray = res;
                  //  console.log(res)
                   // console.log(picArray.join(","))
                    if(picArray.length!=0){
                        requestAddPic(book_id, picArray.join(","));
                    }else{
                        show_msg('操作成功', responseUrl);
                    }

                } else {
                    show_err_msg('上传子图片失败');
                }
            }).fail(function (res) {
                show_err_msg('上传图片失败');
            });

    }

    //添加图片路径到pic  将名字添加到数据库
    function requestAddPic(book_id, picArray) {
        //ajax请求servlet
        var url = "${pageContext.request.contextPath}/AddBookController/addBookPic";
        var data = {
            book_id: book_id,
            picArray: picArray
        };

        $.post(url, data, function (response) {
            console.log(response)
            //var jsonData = $.parseJSON(response);
            var jsonData = response;
            var responseUrl = "${pageContext.request.contextPath}/AddBookController/forward";
            if (jsonData.effectRow>0) {
                //show_err_msg('测试成功');
                show_msg('操作成功', responseUrl);
            } else {
                show_err_msg('操作失败');
            }

        });
    }


</script>

</body>
</html>
